<?php

namespace App\Jobs;

use App\BO\OrderStatus\OrderStatus;
use App\Entities\OrderEntity;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * 订单过期末支付操作
 * Class ExpireOrder
 * @package App\Jobs
 */
class ExpireOrder implements ShouldQueue
{
    use Dispatchable; use InteractsWithQueue; use Queueable; use SerializesModels;

    /**
     * 任务可以尝试的最大次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * @var int
     */
    protected $orderId;

    /**
     * Create a new job instance.
     * @param int $orderId
     */
    public function __construct(int $orderId)
    {
        $this->orderId = $orderId;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \Exception
     */
    public function handle()
    {
        try {
            $order = OrderEntity::find($this->orderId);
        } catch (\Exception $e) {
            Log::info('订单异常');
            return;
        }
        if (is_null($order)) {
            Log::info('订单不存在');
            return;
        }

        $orderStatus = new OrderStatus($order);
        if ($orderStatus->isPending()) {  // 如果订单还是待支付状态
            try {
                Log::info('订单' . $this->orderId . '开始过期处理');
                $orderStatus->getOrderStateContext()->expire();
                Log::info('订单' . $this->orderId . '完成过期处理');
            } catch (\Exception $e) {
                Log::warning('订单过期异常' . $e->getMessage());
            }
        } else {
            Log::info($order->getId() . '订单不是待付款状态，不进行过期处理');
        }
    }
}
